package com.zzyl.quartz.task;

import cn.hutool.core.collection.CollUtil;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.oss.AliyunOSSOperator;
import com.zzyl.oss.AliyunOSSProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
@Slf4j
public class ClearGarbageFileTask {
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Autowired
    private AliyunOSSOperator aliyunOSSOperator;
    @Autowired
    private AliyunOSSProperties aliyunOSSProperties;


    @Scheduled(cron = "0 0 3 * * ?")
    public void clearGarbageFile() {
        try {
            log.info("开始执行定时任务，清理垃圾文件");
            Set<Object> members = redisTemplate.opsForSet().members(CacheConstants.GARBAGE_FILE);
            if (CollUtil.isEmpty( members)){
                log.info("没有垃圾文件");
                return;
            }
            for (Object member : members) {
                //删除文件
                String endpoint = aliyunOSSProperties.getEndpoint();
                String bucketName = aliyunOSSProperties.getBucketName();
                String str= endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/";
                String objectName = member.toString().replace(str, "");
                aliyunOSSOperator.delete(objectName);
                log.info("删除垃圾文件：{}", member);
            }
            redisTemplate.delete(CacheConstants.GARBAGE_FILE);
            log.info("完成定时任务，清理垃圾文件");
        }catch (Exception e){
            e.getMessage();
            log.error("定时任务执行异常：{}", e.getMessage());
        }

    }
}
